// index.js
Page({
  data: {
    fromAddress: {},
    toAddress: {},
    distance: {},
  },

  // 获取位置
  getlocation(e) {
    let { id } = e.currentTarget.dataset;
    console.log(id)
    let that = this;
    wx.getLocation({
      type: 'wgs84', //wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success(res) {
        const { latitude, longitude } = res
        console.log(res)
        wx.chooseLocation({
          latitude,
          longitude,
          success(r) {
            console.log(r)
            if (id == 1) {
              that.setData({ fromAddress: r })
            } else {
              that.setData({ toAddress: r })
            }
          }
        })
      }
    })
  },

  // 计算距离
  calculateDistance() {
    let { fromAddress, toAddress } = this.data;
    let lat1 = fromAddress.latitude;
    let lng1 = fromAddress.longitude;
    let lat2 = toAddress.latitude;
    let lng2 = toAddress.longitude;
    var rad1 = lat1 * Math.PI / 180.0;
    var rad2 = lat2 * Math.PI / 180.0;
    var a = rad1 - rad2;
    var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    var r = 6378137;
    var d = (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0)
    console.log('两点距离是：' + d + '米；' + (d / 1000).toFixed(2) + '公里')
    let distance = { m: d, km: (d / 1000).toFixed(2) }
    this.setData({ distance });
  },

  onLoad() {

  },

})
